
import Vue from 'vue'
import VueRouter from 'vue-router'

import Home from '../views/Home'
import Login from '../views/Login'

import Statics from '../views/statics/Statics'
import User from '../views/user/User'
import Roles from '../views/user/Roles'

// 使用路由
Vue.use(VueRouter)

// 以下代码为了解决冗余导航问题，也就是说一开始我们登录之后跳转的页面是home页面
// 当前显示的虽然是user组件，但他也是home页面，所以，出现了冗余导航问题，加上以下代码即可
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}


const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  }, {
    path: '/home',
    component: Home,
    // meta就是路由元信息，也就是路由配置多携带的参数
    meta: {
      name: '应用管理',
      id: 1,
      iconclass: 'el-icon-user-solid'
    },
    redirect: '/home/user',//重定向user组件，跳到首页之后显示user组件
    children: [//子路由
      { path: '/home/statics', component: Statics },
      {
        path: '/home/user',
        component: User,
        meta: { name: '用户管理', id: 2 }
      },
      {
        path: 'home/roles',
        component: Roles,
        meta: { name: '角色管理', id: 3 }
      }
    ]


  },
  // 跳出home，跟home并列编写
  {
    path: '/log',
    meta: { name: '日志管理', id: 4, iconclass: 'el-icon-s-order' },
    children: [
      { path: '/log/syslog', meta: { name: '系统日志', id: 5 } },
      { path: '/log/oplog', meta: { name: '管理员日志', id: 6 } },
      { path: '/log/userlog', meta: { name: '用户统计行为', id: 7 } },
    ]
  }

]

const router = new VueRouter({
  mode: 'hash', // 默认是hash地址
  routes
})

export default router

// 路由守卫
router.beforeEach((to, from, next) => { //去哪里 从哪来  继续执行
  if (to.path === '/login') {
    if (sessionStorage.getItem('username')) {
      // 说明已经登录了
      router.push('/home')
    } else {
      // 没登录  原地停留
      next()
    }
  }

  if (sessionStorage.getItem('username')) {
    next() //放行
  } else {
    router.push('/login')
  }

})
